import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.TooManyListenersException;


public class ProtocolHandler implements SerialPortEventListener {
	
	private SerialCommunication serial;
	private String inputLine;
	private boolean isDataAvailable;

	public ProtocolHandler(SerialCommunication serial){
		inputLine = "";
		isDataAvailable = false;
		this.serial = serial;
		try {
			serial.serialPort.addEventListener(this);
		} catch (TooManyListenersException e) {
			e.printStackTrace();
		}
	}
	
	public double requestDouble(String command){
		try {
			write(command);
			while(!isDataAvailable){
				Thread.sleep(100);
			}
			String[] split = inputLine.split(":");
			return Double.parseDouble(split[1]);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public double requestSetDouble(String command, int param, double value){
		if(!command.endsWith(":")){
			command += "\n";
		}
		try {
			write(command+param+value);
			while(!isDataAvailable){
				Thread.sleep(100);
			}
			return Double.parseDouble(inputLine);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public void write(String message) throws IOException{
		if(!message.endsWith("\n")){
			message += "\n";
		}
		serial.serialPort.getOutputStream().write(message.getBytes(Charset.forName("US-ASCII")));
	}


	/**
	 * Handle an event on the serial port. Read the data and print it.
	 */
	public synchronized void serialEvent(SerialPortEvent oEvent) {
		if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			try {
				inputLine = serial.getInput().readLine();
				isDataAvailable = true;
				System.out.println(inputLine);
			} catch (Exception e) {
				System.err.println(e.toString());
			}
		}
		// Ignore all the other eventTypes, but you should consider the other ones.
	}
}
